package com.tckdq.tcc.service.impl;

import com.tckdq.tcc.doc.CourseDoc;
import com.tckdq.tcc.dto.SearchCourseParams;
import com.tckdq.tcc.mapper.HighlightResultMapper;
import com.tckdq.tcc.repository.CourseRespository;
import com.tckdq.tcc.result.PageList;
import com.tckdq.tcc.service.IEsCourseService;
import com.tckdq.tcc.vo.AggPageList;
import com.tckdq.tcc.vo.BucketVO;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.*;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.aggregations.support.ValueType;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.swing.*;
import java.util.*;

@Service
@Slf4j
public class EsCourseServiceImpl implements IEsCourseService {

    @Autowired
    private CourseRespository respository;
    @Autowired
    private ElasticsearchRestTemplate restTemplate;
    @Autowired
    private HighlightResultMapper highlightResultMapper;
    @Override
    public void save(CourseDoc doc) {
        respository.save(doc);
    }

    @Override
    public void delete(Long id) {
        respository.deleteById(id);
    }

    @Override
    public PageList searchCourse(SearchCourseParams dto) {
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        //分页
        builder.withPageable(PageRequest.of(dto.getPage() - 1, dto.getRows()));

        if (StringUtils.hasLength(dto.getSortField())) {
            String sortFieldName = getSortFielName(dto.getSortField());
            SortOrder sortOrder = getSortFielType(dto.getSortType());
            builder.withSort(new FieldSortBuilder(sortFieldName).order(sortOrder));
        }
        //查询条件
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        if (StringUtils.hasLength(dto.getKeyword())) {
            boolQuery.must(QueryBuilders.matchQuery("name", dto.getKeyword()));
        }
        if (StringUtils.hasLength(dto.getGradeName())) {
            boolQuery.filter(QueryBuilders.termQuery("gradeName", dto.getGradeName()));
        }

        if (StringUtils.hasLength(dto.getChargeName())) {
            boolQuery.filter(QueryBuilders.termQuery("chargeName", dto.getChargeName()));
        }

        if (dto.getPriceMax() != null) {
            boolQuery.filter(QueryBuilders.rangeQuery("priceMax").lte(dto.getPriceMax()));
        }

        if (dto.getPriceMin() != null) {
            boolQuery.filter(QueryBuilders.rangeQuery("priceMin").gte(dto.getPriceMin()));
        }

        builder.withQuery(boolQuery);
        // 1.添加聚合
        builder.addAggregation(AggregationBuilders.terms("gradeNameAgg").field("gradeName").order(BucketOrder.count(false)));
        builder.addAggregation(AggregationBuilders.terms("chargeNameAgg").field("chargeName").order(BucketOrder.count(false)));
        //高亮
        HighlightBuilder.Field field = new HighlightBuilder.Field("name");
        field.preTags("<font style='color:red'>").postTags("</font>");
        builder.withHighlightFields(field);

        SearchQuery searchquery = builder.build();
        //respository.search(searchquery);
        AggregatedPage<CourseDoc> page = restTemplate.queryForPage(searchquery, CourseDoc.class, highlightResultMapper);

        //2.聚合
        Aggregations aggregations = page.getAggregations();
        //聚合结果类似map的形式--entry:"aggTerm":{Aggration},entry:"aggTerm":{Aggration}
        Map<String, Aggregation> aggregationMap = aggregations.asMap();

        HashMap<String, List<BucketVO>> aggResultMap = new HashMap<>();

        aggregationMap.entrySet().forEach(entry ->{
            String key = entry.getKey();//gradeNameAgg
            ParsedStringTerms parsedStringTerms = (ParsedStringTerms) entry.getValue();
            log.info("key {} ,value {}",key,parsedStringTerms);
            List<? extends Terms.Bucket> buckets = parsedStringTerms.getBuckets();
            //用来装buckets列表
            List<BucketVO> bucketVOList = new ArrayList<>();

            buckets.forEach(bucket ->{
                String keyAsString = bucket.getKeyAsString();
                long docCount = bucket.getDocCount();
                log.info("keyAsString {},docCount {}",keyAsString,docCount);
                bucketVOList.add(new BucketVO(keyAsString,docCount));
            });
            //再把entry的key和value装进aggResultMap
            aggResultMap.put(key,bucketVOList);
        });

        return new AggPageList(page.getTotalElements(), page.getContent(),aggResultMap);
    }

    private SortOrder getSortFielType(String sortType) {
        return sortType == null || sortType.toLowerCase().equals("desc") ? SortOrder.DESC : SortOrder.ASC;
    }

    private String getSortFielName(String sortField) {
        switch (sortField.toLowerCase()) {
            case "xp":
                return "onlineTime";
            case "xl":
                return "saleCount";
            case "pl":
                return "commentCount";
            case "jg":
                return "price";
            case "rq":
                return "viewCount";
        }
        return "price";
    }
}
